package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        notice.setCreat_time(new Date());
        notice.setEmployee(UserContext.getCurrentEmployee());
        notice.setRead_status(false);
        notice.setPublish_status(false);
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    //更新用户的查看公告
    @Override
    public void updateNotice(Long id) {
        List<Long> notices;
        //如果是管理员则添加全部（发布，没发布）
        if (UserContext.getCurrentEmployee().isAdmin()){
           notices = noticeMapper.selectAllByPublish2();
        }else{   //不是则查找已经发布的
            //首先获取所有的已经发布的公告
             notices = noticeMapper.selectAllByPublishTrue();
        }
        //拿到用户所有的已经发布的公告
        List<Long> employeEnotices = noticeMapper.selectByEmployeeId(id);
        //更新用户的公告，进行对比公告id，如果没有则添加关联关系
        for (Long nId :notices){
            if (employeEnotices.contains(nId)) {
                continue;
            }else {
                noticeMapper.insertRelation(id, nId);
            }
        }
    }

    @Override
    public void UpdateReadStatus(Long noticeId, Long employeeId, Long readStatus) {
        noticeMapper.UpdateReadStatus(noticeId, employeeId, readStatus);
    }

    @Override
    public void updatePublish(Long id, boolean publishStatus) {
        noticeMapper.updatePublish(id, publishStatus);
    }

    @Override
    public int selectNoRead(Long id) {
        return noticeMapper.selectNoRead(id);
    }


}
